package john.walker;

import java.io.PrintWriter;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

import com.alibaba.druid.util.JMXUtils;

import john.walker.config.XmlFileLoader;
import john.walker.filter.ConfigurableStackTraceFilter;
import john.walker.filter.DefaultStackTraceFilter;
import john.walker.filter.StackTraceFilter;
import john.walker.jmx.ProxyStatManager;
import john.walker.log.LogFactory;

/**
 * Connection连接代理类
 *
 * @author Johnnie Walker
 *
 */
public class ProxyConnection implements Connection {

	private static List<StackTraceFilter> stackTraceFilters = new ArrayList<StackTraceFilter>(3);

	private static StackTraceFilter defaultStackTraceFilter = new DefaultStackTraceFilter();

	static {
		// 加载默认过滤器
		addStackTraceFilter(defaultStackTraceFilter);
		// 加载可配置过滤器
		addStackTraceFilter(new ConfigurableStackTraceFilter(
				XmlFileLoader.loadFilterWords()));

		// 加载日志组件
		XmlFileLoader.loadLoggers();

		JMXUtils.register("john.walker:type=ProxyStat", ProxyStatManager.getInstance());
	}

	private Connection con      = null;


	/**
	 * 数据库连接栈
	 */
	private StackTraceElement[] connectionStackTrace;


	public ProxyConnection(Connection con) {
		this.con = con;
		this.connectionStackTrace = Thread.currentThread().getStackTrace();
		Monitor.getMonitor().addConnection(this);
	}

	// 覆盖jdbc驱动类方法


	@Override
	public void abort(Executor executor) throws SQLException {
		this.con.abort(executor);
	}


	@Override
	public void clearWarnings() throws SQLException {
		this.con.clearWarnings();
	}


	@Override
	public void close() throws SQLException {
		this.con.close();
		Monitor.getMonitor().removeConnection(this);
	}


	@Override
	public void commit() throws SQLException {
		this.con.commit();
	}


	@Override
	public Array createArrayOf(String typeName, Object[] elements)
			throws SQLException {
		return this.con.createArrayOf(typeName, elements);
	}


	@Override
	public Blob createBlob() throws SQLException {
		return this.con.createBlob();
	}


	@Override
	public Clob createClob() throws SQLException {
		return this.con.createClob();
	}


	@Override
	public NClob createNClob() throws SQLException {
		return this.con.createNClob();
	}


	@Override
	public SQLXML createSQLXML() throws SQLException {
		return this.con.createSQLXML();
	}


	@Override
	public Statement createStatement() throws SQLException {
		return new ProxyStatement(this.con.createStatement());
	}


	@Override
	public Statement createStatement(int resultSetType, int resultSetConcurrency)
			throws SQLException {
		return new ProxyStatement(this.con.createStatement(resultSetType,
				resultSetConcurrency));
	}


	@Override
	public Statement createStatement(int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
					throws SQLException {
		return new ProxyStatement(this.con.createStatement(resultSetType,
				resultSetConcurrency, resultSetHoldability));
	}


	@Override
	public Struct createStruct(String typeName, Object[] attributes)
			throws SQLException {
		return this.con.createStruct(typeName, attributes);
	}


	@Override
	public boolean getAutoCommit() throws SQLException {
		return this.con.getAutoCommit();
	}


	@Override
	public String getCatalog() throws SQLException {
		return this.con.getCatalog();
	}


	@Override
	public Properties getClientInfo() throws SQLException {
		return this.con.getClientInfo();
	}


	@Override
	public String getClientInfo(String name) throws SQLException {
		return this.con.getClientInfo(name);
	}


	@Override
	public int getHoldability() throws SQLException {
		return this.con.getHoldability();
	}


	@Override
	public DatabaseMetaData getMetaData() throws SQLException {
		return this.con.getMetaData();
	}


	@Override
	public int getNetworkTimeout() throws SQLException {
		return this.con.getNetworkTimeout();
	}


	@Override
	public String getSchema() throws SQLException {
		return this.con.getSchema();
	}


	@Override
	public int getTransactionIsolation() throws SQLException {
		return this.con.getTransactionIsolation();
	}


	@Override
	public Map<String, Class<?>> getTypeMap() throws SQLException {
		return this.con.getTypeMap();
	}


	@Override
	public SQLWarning getWarnings() throws SQLException {
		return con.getWarnings();
	}


	@Override
	public boolean isClosed() throws SQLException {
		return this.con.isClosed();
	}


	@Override
	public boolean isReadOnly() throws SQLException {
		return this.con.isReadOnly();
	}


	@Override
	public boolean isValid(int timeout) throws SQLException {
		return this.con.isValid(timeout);
	}


	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return this.con.isWrapperFor(iface);
	}


	@Override
	public String nativeSQL(String sql) throws SQLException {
		return this.con.nativeSQL(sql);
	}


	@Override
	public CallableStatement prepareCall(String sql) throws SQLException {
		return new ProxyCallableStatement(this.con.prepareCall(sql), sql);
	}


	@Override
	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {
		return new ProxyCallableStatement(this.con.prepareCall(sql,
				resultSetType, resultSetConcurrency), sql);
	}


	@Override
	public CallableStatement prepareCall(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
					throws SQLException {

		return new ProxyCallableStatement(this.con.prepareCall(sql,
				resultSetType, resultSetConcurrency, resultSetHoldability), sql);
	}


	@Override
	public PreparedStatement prepareStatement(String sql) throws SQLException {

		return new ProxyPreparedStatement(this.con.prepareStatement(sql),
				sql);
	}


	@Override
	public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
			throws SQLException {

		return new ProxyPreparedStatement(this.con.prepareStatement(sql,
				autoGeneratedKeys), sql);
	}


	@Override
	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency) throws SQLException {

		return new ProxyPreparedStatement(this.con.prepareStatement(sql,
				resultSetType, resultSetConcurrency), sql);
	}


	@Override
	public PreparedStatement prepareStatement(String sql, int resultSetType,
			int resultSetConcurrency, int resultSetHoldability)
					throws SQLException {

		return new ProxyPreparedStatement(this.con.prepareStatement(sql,
				resultSetType, resultSetConcurrency, resultSetHoldability), sql);
	}


	@Override
	public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
			throws SQLException {

		return new ProxyPreparedStatement(this.con.prepareStatement(sql,
				columnIndexes), sql);
	}


	@Override
	public PreparedStatement prepareStatement(String sql, String[] columnNames)
			throws SQLException {

		return new ProxyPreparedStatement(this.con.prepareStatement(sql,
				columnNames), sql);
	}


	@Override
	public void releaseSavepoint(Savepoint savepoint) throws SQLException {
		this.con.releaseSavepoint(savepoint);
	}


	@Override
	public void rollback() throws SQLException {
		this.con.rollback();
	}


	@Override
	public void rollback(Savepoint savepoint) throws SQLException {
		this.con.rollback(savepoint);
	}


	@Override
	public void setAutoCommit(boolean autoCommit) throws SQLException {
		this.con.setAutoCommit(autoCommit);
	}


	@Override
	public void setCatalog(String catalog) throws SQLException {
		this.con.setCatalog(catalog);
	}


	@Override
	public void setClientInfo(Properties properties)
			throws SQLClientInfoException {
		this.con.setClientInfo(properties);
	}


	@Override
	public void setClientInfo(String name, String value)
			throws SQLClientInfoException {
		this.con.setClientInfo(name, value);
	}


	@Override
	public void setHoldability(int holdability) throws SQLException {
		con.setHoldability(holdability);
	}


	@Override
	public void setNetworkTimeout(Executor executor, int milliseconds)
			throws SQLException {
		this.con.setNetworkTimeout(executor, milliseconds);
	}


	@Override
	public void setReadOnly(boolean readOnly) throws SQLException {
		this.con.setReadOnly(readOnly);
	}


	@Override
	public Savepoint setSavepoint() throws SQLException {
		return this.con.setSavepoint();
	}


	@Override
	public Savepoint setSavepoint(String name) throws SQLException {
		return this.con.setSavepoint(name);
	}


	@Override
	public void setSchema(String schema) throws SQLException {
		this.con.setSchema(schema);
	}


	@Override
	public void setTransactionIsolation(int level) throws SQLException {
		this.con.setTransactionIsolation(level);
	}


	@Override
	public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
		this.con.setTypeMap(map);
	}


	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return this.con.unwrap(iface);
	}

	/**
	 * synchronized 保证并发情况下，日志打印顺序的正确性
	 *
	 * @param stmt
	 * @param sql
	 * @param parameters
	 * @param start
	 * @param end
	 */
	public synchronized static void printSQL(Statement stmt, String sql, Object[] parameters, long start, long end) {

		if(!ProxyStatManager.getInstance().isPrintLog()) {
			return ;
		}

		if(!XmlFileLoader.sqlMonitor()) {
			return;
		}

		long time = end - start;
		if( time < XmlFileLoader.sqlMonitorTime()) {
			return ;
		}

		Class<?> c = stmt.getClass();
		boolean isOriginalStmt = false;
		do {
			if (c.getName().startsWith("com.mysql.jdbc")
					|| c.getName().startsWith("org.apache.derby")
					|| c.getName().startsWith("oracle.jdbc")) {
				isOriginalStmt = true;
				break;
			}
			c = c.getSuperclass();
		} while (c.getSuperclass() != null);

		if (isOriginalStmt) {
			LogFactory.getLogger().log("SQL代理： " + sql);
			if(parameters != null && parameters.length > 0) {
				LogFactory.getLogger().log("SQL参数： " + Arrays.toString(parameters));
			}

			String format = "";
			if(time < 1000) {
				format = time + "毫秒";
			} else if(time < 60000) {
				format = ((double) time) / 1000 + "秒";
			} else if(time < 3600000) {
				format = ((double) time) / 60000 + "分钟";
			} else {
				format = ((double) time) / 3600000 + "小时";
			}
			LogFactory.getLogger().log("SQL耗时： " + format);
			if (XmlFileLoader.sqlMonitorStack()) {
				LogFactory.getLogger().log("调用栈如下：");
				printStackTrace();
			}
			LogFactory.getLogger().newLine();
		}

	}



	/**
	 * @param stmt
	 * @param sql
	 * @param start
	 * @param end
	 */
	public static void printSQL(Statement stmt, String sql, long start, long end) {
		printSQL(stmt, sql, null, start, end);
	}

	/**
	 * 打印执行栈调用
	 *
	 * @return
	 */
	public static void printStackTrace() {
		StackTraceElement[] elements = Thread.currentThread().getStackTrace();
		for (StackTraceElement e : elements) {
			boolean accpet = true;
			for(StackTraceFilter filter : stackTraceFilters) {
				if(!filter.accpet(e.getClassName(), e.getMethodName())) {
					accpet = false;
					break;
				}
			}
			if(accpet) {
				LogFactory.getLogger().log(e.getClassName() + "." + e.getMethodName() + ":" + e.getLineNumber());
			}
		}
	}

	public static List<StackTraceFilter> getStackTraceFilters() {
		return stackTraceFilters;
	}

	public static void addStackTraceFilter(final StackTraceFilter stackTraceFilter) {
		synchronized (stackTraceFilters) {
			ProxyConnection.stackTraceFilters.add(stackTraceFilter);
		}
	}

	/**
	 * 增加过滤器
	 *
	 * 1、 *com.san30.XXXClass   过滤以com.san30.XXXClass结尾的类
	 * 2、 com.san30*            过滤以com.san30开头类
	 * 3、 *$$EnhancerByCGLIB$$* 过滤包含$$EnhancerByCGLIB$$的类（hibernate生成）
	 *
	 * @param stackTraceFilterWords 需要过滤的单词组
	 */
	public static void addStackTraceFilterWords(final List<String> stackTraceFilterWords) {
		if(stackTraceFilterWords != null) {
			addStackTraceFilter(new ConfigurableStackTraceFilter(stackTraceFilterWords));
		}
	}


	/**
	 * 打印连接栈调用
	 */
	public void printConnectionStackTrace(PrintWriter out) {
		if(this.connectionStackTrace != null) {
			for (StackTraceElement e : connectionStackTrace) {
				if(defaultStackTraceFilter.accpet(e.getClassName(), e.getMethodName())) {
					out.println(e.toString());
				}
			}
		}
	}
}
